package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.TemplateDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Template;
import com.itheima.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: qingcheng
 * @description: 模板接口实现类
 * @author: Mr.Gu
 * @create: 2021-07-17 15:12
 **/
@Service(interfaceClass = TemplateService.class)
@Transactional
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TemplateDao templateDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //当前页码
        Integer currentPage = queryPageBean.getCurrentPage();
        //每页显示的记录数
        Integer size = queryPageBean.getPageSize();
        //查询条件
        String searchMap = queryPageBean.getSearchMap();


        //开启分页
        PageHelper.startPage(currentPage,size);
        //调用dao层方法
        Page<Template> templates = templateDao.selectByCondition(searchMap);

        //返回
        return new PageResult(templates.getTotal(),templates.getResult());
    }






    /**
     * 新增
     * @param template
     */
    @Override
    public void add(Template template) throws RuntimeException{
        long count = templateDao.selectByName(template.getName());
        if (count > 0){
            throw  new RuntimeException(template.getName()+"已存在,添加失败");
        }
        templateDao.add(template);
    }

    @Override
    public void delete(Integer id) throws RuntimeException{
        //判断是否有数据存在关联表中
        long count = templateDao.selectByTemplateId(id);
        if(count > 0){
            throw new RuntimeException("删除失败");
        }
        templateDao.delete(id);
    }

    @Override
    public Template findById(Integer id) {
        return templateDao.findById(id);

    }

    @Override
    public void update(Template template) throws RuntimeException{
        //判断修改后的name是否已存在
        long count = templateDao.selectByName(template.getName());
        if(count > 0){
            throw new RuntimeException("已存在,修改失败或与原数据一致");
        }
        templateDao.update(template);
    }
}
